from pymongo import MongoClient
from pymongo.errors import ConnectionFailure
from pprint import pprint
# MongoDB连接配置
MONGO_HOST = "101.227.69.34"
MONGO_PORT = 2929
MONGO_USER = "admin"
MONGO_PASS = "admin"
DB_NAME = "hr"  # 指定数据库名
COLLECTION_NAME = "employees"  # 指定集合名
try:
    # 创建MongoDB客户端连接
    client = MongoClient(
        host=MONGO_HOST,
        port=MONGO_PORT,
        username=MONGO_USER,
        password=MONGO_PASS,
        authSource="admin",
        connectTimeoutMS=5000
    )
    # 测试连接
    client.admin.command("ping")
    print("MongoDB连接成功！")
    # 获取数据库和集合
    db = client[DB_NAME]
    collection = db[COLLECTION_NAME]
    #构建查询条件
    query = {
        "age":{"$gte":25},
        "salary":{"$gte":3500}
    }
    #执行查询
    print("\n查询结果(age>=25 且 salary>=3500):")
    results = collection.find(query)

    #打印结果
    for i, doc in enumerate(results,1):
        print(f"\n记录 #{i}:")
        pprint(doc)
except ConnectionFailure as e:
    print(f"MongoDB连接失败: {e}")
except Exception as e:
    print(f"发生错误: {e}")
    import traceback
    traceback.print_exc() #打印完整的错误堆栈
finally:
    # 关闭连接
    if "client" in locals():
        client.close()